package mts.testframework.testitems;

import java.util.Calendar;

import mts.ElevatorControllerInternalConnection;
import mts.NewEventTimestampListener;
import mts.constants.EventType;
import mts.messages.EventTimeStampMessage;
import mts.messages.FloorRequestMessage;

public class HallCallTestItem extends TestItem implements NewEventTimestampListener {

	
	private byte floor;
	
	boolean alreadyCompleted = false;
	
	
	public HallCallTestItem(long delay, byte car, byte floor, TestItem... onCompleted) {
		super(delay, onCompleted);
		this.car = car;
		this.floor = floor;
		
		startTime = Calendar.getInstance().getTime();
	}
	
	@Override
	public void start() {
		
		ElevatorControllerInternalConnection elevatorControllerInternalConnection = testItemScheduler.getElevatorControllerInternalConnectionServer().getElevatorControllerInternalConnection(car); 
		
		elevatorControllerInternalConnection.addOonNewEventTimestampListener(this);
		
		elevatorControllerInternalConnection.sendMessage(new FloorRequestMessage(this.floor));
	}

	@Override
	public void addEventTimeStamp(EventTimeStampMessage eventTimeStampMessage) {
		if (eventTimeStampMessage.getCurrentFloor() == this.floor  && eventTimeStampMessage.getEvent() == EventType.ARRIVAL) {
			complete();	
		}
		
	}
	
	@Override
	public void complete() {
		synchronized(this) {
			if (alreadyCompleted) {
				return;
			}
			alreadyCompleted = true;
		}
		endTime = Calendar.getInstance().getTime();
		testItemScheduler.logOutput(String.format("%d MV_TIME %d\n", id, getDeltaTime()  ));
		
		ElevatorControllerInternalConnection elevatorControllerInternalConnection = testItemScheduler.getElevatorControllerInternalConnectionServer().getElevatorControllerInternalConnection(car); 
		
		elevatorControllerInternalConnection.removeOnNewEventTimestampListener(this);
		
		super.complete();
	}
	
	
}
